package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.dao.*;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.OrderBill;
import com.cjzuji.rental.pojo.Orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class GCLingLSaveServiceImpl {
    @Autowired
    GCLingLOrderDao gCLingLOrderDao;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderBillMapper orderBillMapper;
    @Autowired
    LingLUserDao lingLUserDao ;
    @Autowired
    LingLContractDao lingLContractDao;
    @Autowired
    LingLBillDao lingLBillDao ;

    private static final Logger logger = LoggerFactory.getLogger(GCLingLSaveServiceImpl.class);
    //抽离保存save
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void getListSave(String orderId, Map<String, Object> item, Double screenRisksAmount,
                            int screenRisksType, Map<String,Object> ordercontract, Map<String,Object> billMap) {
        try {
            //账单最后一期买断价
            Double outBuyoutAmount = 0.0;
            Map<String,Object> outBuyoutAmountMap = (Map<String, Object>) billMap.get("userOrderCashesDto");
            outBuyoutAmount = Double.parseDouble(outBuyoutAmountMap.get("buyOutAmount").toString());
            // 判断 当前的订单号是否在数据库中存在
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",orderId);
            List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
            logger.info("existingOrder {}",existingOrder);
            if (existingOrder.size() > 0 ) {
                logger.info("订单已存在");
            }
            else{
                System.out.println("进去开始保存order~~~~~~~~~~~~~~");
                Long orderID = gCLingLOrderDao.save(item,screenRisksAmount,screenRisksType,outBuyoutAmount);
                lingLUserDao.save(item,orderID);
                if (item.get("expressNo") != null && !"EXPRESS".equals(item.get("expressNo"))){

                    System.out.println("进去开始保存contract~~~~~~~~~~~~~~"+orderID);
                    lingLContractDao.save(ordercontract,orderID);

                    if (billMap != null){
                        List<Map<String, Object>> orderBill = (List<Map<String, Object>>) billMap.get("orderByStagesDtoList");
                        // logger.info("orderBill {}",orderBill);
                        System.out.println("进去开始保存bill~~~~~~~~~~~~~~"+orderID);
                        lingLBillDao.save(orderBill, orderID);
                        System.out.println("保存成功~~~~~~~~~~~~~~~~~~s"+orderID);
                    }
                }
            }
        } catch (Exception e) {
            // 回滚事务
//            transactionManager.rollback(status);
            logger.error("保存数据时发生异常~~~~~~~~~~~~", e);
            throw new RuntimeException(e); // 确保抛出异常以回滚事务
        }
    }

    //租用中更新账单和合同
    public void getzySave(String orderId, Map<String, Object> item,Map<String,Object> ordercontract,List<Map<String,Object>> orderBill) {
        try {
            // 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
            QueryWrapper<OrderBill> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orders_id",orderId);
            // logger.info("orderBill {}",orderBill);
            //更新orders表的状态为3,更新快递单号，更新时间
            UpdateWrapper<Orders> updataWrapper = new UpdateWrapper<>();
            updataWrapper.eq("order_id",orderId)
                    .set("status",3)
                    .set("delivery_no", item.get("logisticsNo")==null?"":item.get("logisticsNo").toString())
                    .set("update_time",new Date());
            orderMapper.update(updataWrapper);
            List<OrderBill> existingBill = orderBillMapper.selectList(queryWrapper);
            logger.info("查询到的已存在账单数量: {}",existingBill.size());
            // 订单已存在
            if (!existingBill.isEmpty() ) {
                Long orderID = existingBill.get(0).getOrderId();
                // 订单已存在，对比两方的“还款状态”数据，如果相同不变，不同对数据库账单表进行更新
                logger.info("订单已存在~~,对比更新数据",orderId);
                compareUpdate(orderBill,existingBill,orderID);
            }
            else{
                QueryWrapper<Orders> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("order_id",orderId);
                Orders order = orderMapper.selectOne(orderWrapper);
                if(order != null){
                    Long orderID = order.getId();
                    logger.info("添加合同表~~",orderId);
                    lingLContractDao.save(ordercontract,orderID);
                    logger.info("添加账单表~~",orderId);
                    lingLBillDao.save(orderBill, orderID);
                }else {
                    logger.info("Orders表中未找到订单~~~",orderId);
                }// 手动提交事务
                logger.info("事务提交成功！");
            }
        } catch (Exception e) {
            // 回滚事务
//            transactionManager.rollback(status);
            logger.error("保存数据时发生异常~~~~~~~~~~~~", e);
            throw new RuntimeException(e); // 确保抛出异常以回滚事务
        }
    }
    //对比更新代码
    public void compareUpdate(List<Map<String, Object>> billDtoList, List<OrderBill> existingBill, Long orderID) {
        //System.out.println("billDtoList~~:"+billDtoList);
        //创建一个Map，用于存储数据库中的账单
        Map<Integer, OrderBill> existingBillMap = new HashMap<>();
        for (OrderBill bill : existingBill) {
            existingBillMap.put(bill.getTerm(), bill);
        }
        //logger.info("existingBillMap {}",existingBillMap);
        for (Map<String, Object> billDto : billDtoList) {
            int term = Integer.parseInt(billDto.get("currentPeriods").toString()) ;
            String newStatus = "未支付";
            if ("3".equals(billDto.get("debitStatus").toString())){
                newStatus = "已支付";
            }else if ("3".equals(billDto.get("status").toString())){
                newStatus = "逾期已支付";
            }

            OrderBill oldBill = existingBillMap.get(term);
            if (oldBill != null) {
                //对比订单状态
                String oldStatus = oldBill.getRepayStatusStr() != null ? oldBill.getRepayStatusStr() : "";
                //System.out.println("oldStatus~~ " + oldStatus);
                if(!newStatus.equals(oldStatus)){
                    //状态不同
                    logger.info("状态不同，第{}期~~", term);
                    UpdateWrapper<OrderBill> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", oldBill.getId())
                            .set("real_pay_time", billDto.get("repaymentDate")) //支付时间
                            .set("real_pay_capital", billDto.get("currentPeriodsRent"))  //还款金额
                            .set("repay_status_str", newStatus) // 还款状态  3 已支付  1 未支付
                            .set("real_pay_trade_id", billDto.get("tradeNo"))  //商家交易号
                            .set("real_repay_time", billDto.get("repaymentDate"))//还款时间
                            .set("update_time", new Date());
                    orderBillMapper.update(null,updateWrapper);
                }else {
                    //logger.info("状态相同，第{}期~~", term);
                }
            }
        }
    }
}
